import 'package:eleapp/controller/usercontroller.dart';
import 'package:eleapp/pages/tabs/tabs.dart';
import 'package:eleapp/res/colors.dart';
import 'package:eleapp/res/strings.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../../dio/http_request.dart';
import '../../dio/api.dart';

import '../../localstorage/storage.dart';
import '../../util/formatter/customized_length_formatter.dart';
import '../../util/formatter/customized_text_formatter.dart';

class Login extends StatefulWidget {
  const Login({super.key});

  @override /*  */
  State<Login> createState() => _LoginState();
}

class _LoginState extends State<Login> {
  var username = TextEditingController();
  var password = TextEditingController();

  UserController userController = Get.find();
  IconController iconController = Get.find();

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () {
        // 收回键盘
        FocusScope.of(context).requestFocus(FocusNode());
      },
      child: Scaffold(
        appBar: AppBar(
          title: Text(
            StringStyles.login.tr,
            style: const TextStyle(color: Colors.white),
          ),
          backgroundColor: Colors.blue,
          leading: null,
        ),
        body: Container(
          alignment: Alignment.center,
          padding: const EdgeInsets.all(30),
          child: ListView(
            children: [
              const SizedBox(
                height: 60,
              ),
              Text(
                StringStyles.teacherLogin.tr,
                textAlign: TextAlign.center,
                style: const TextStyle(
                    color: Colors.blue,
                    fontSize: 30,
                    fontWeight: FontWeight.w500),
              ),
              const SizedBox(
                height: 20,
              ),
              SizedBox(
                width: 320,
                height: 80,
                child: TextField(
                  controller: username,
                  cursorColor: ColorStyle.thememode_color,
                  decoration: InputDecoration(
                    prefixIcon: const Icon(Icons.person),
                    hintText: StringStyles.inputTeacherAccount.tr,
                    hintStyle: const TextStyle(color: Colors.grey),
                    border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(40)),
                  ),
                ),
              ),
              SizedBox(
                  width: 320,
                  height: 80,
                  child: Stack(
                    children: [
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                        // row组件本身不能设置高度 只能外套一个有高度的容器 这个属性针对外层容器本row的位置
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          // const SizedBox(
                          //   width: 72,
                          //   child: Text('确认密码：'),
                          // ),
                          Expanded(
                            flex: 1,
                            child: Obx(() => TextField(
                                  controller: password,
                                  cursorColor: ColorStyle.thememode_color,
                                  obscureText: !iconController
                                      .loginpwdShow.value, // 隐藏文本内容，用于密码
                                  inputFormatters: [
                                    ///输入长度和格式限制
                                    CustomizedLengthTextInputFormatter(16),
                                    CustomizedTextInputFormatter(
                                      filterPattern: RegExp("[a-zA-Z]|[0-9]"),
                                    ),
                                  ],
                                  onChanged: (value) {
                                    // confirmMethod();
                                  },
                                  decoration: InputDecoration(
                                    // prefixIcon: const Icon(Icons.password_outlined),
                                    hintText: StringStyles.inputPwd.tr,
                                    prefixIcon:
                                        const Icon(Icons.password_outlined),
                                    hintStyle:
                                        const TextStyle(color: Colors.grey),
                                    border: OutlineInputBorder(
                                        borderRadius:
                                            BorderRadius.circular(40)),
                                  ),
                                )),
                          )
                        ],
                      ),
                      Positioned(
                        top: 4,
                        right: 0,
                        child: Obx(() => Visibility(
                              visible: true && true,
                              child: IconButton(
                                icon: Icon(
                                  iconController.loginpwdShow.value
                                      ? Icons.remove_red_eye
                                      : Icons.visibility_off,
                                  size: 24,
                                  color: Colors.black,
                                ),
                                onPressed: () {
                                  iconController.loginpwdShow.value =
                                      !iconController.loginpwdShow.value;
                                },
                              ),
                            )),
                      )
                    ],
                  )
                  // TextField(
                  //   controller: password,
                  //   cursorColor: ColorStyle.thememode_color,
                  //   obscureText: true, // 隐藏文本内容，用于密码
                  //   decoration: InputDecoration(
                  //     prefixIcon: const Icon(Icons.password_outlined),
                  //     hintText: '请输入密码',
                  //     hintStyle: const TextStyle(color: Colors.grey),
                  //     border: OutlineInputBorder(
                  //         borderRadius: BorderRadius.circular(40)),
                  //   ),
                  // ),
                  ),
              Container(
                margin: const EdgeInsets.only(top: 20),
                width: 320,
                child: ElevatedButton(
                    onPressed: () {
                      // 收回键盘
                      FocusScope.of(context).requestFocus(FocusNode());

                      Request.post(Api.login, {
                        'username': username.text,
                        'password': password.text
                      }, success: (Map res) async {
                        if (res.isNotEmpty) {
                          Map myinfo = await Request2.post<Map>(Api.myinfo, {
                            'uid': res['id'],
                          });
                          print(myinfo);

                          if (myinfo['name'] != '') {
                            // 如果没有头像 添加默认头像（ElementUI的默认头像）
                            if (myinfo['avatar'] == '') {
                              myinfo['avatar'] =
                                  'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png';
                            }
                            // 保存数据到全局
                            userController.userAccount.value = username.text;
                            userController.userId.value = res['id'];
                            userController.user.value = myinfo;
                            userController.islogin.value = true;

                            // 初始化用户本地存储操作类
                            Store store = await Store.getInstance();
                            // 保存登录状态、用户数据
                            // 都是异步操作 要await等待完成存储
                            await store.saveString(
                                StringStyles.userAccount, username.text);
                            await store.saveInt(StringStyles.userId, res['id']);
                            await store.saveMap(StringStyles.userInfo, myinfo);
                            await store.saveBoolStatus(
                                StringStyles.islogin, true);

                            print('登录成功');

                            iconController.loginpwdShow.value = false;
                            Get.off(() => Tabs(
                                  tabindex: 2,
                                ));
                          }
                        }
                      });
                      // Navigator.of(context).pushAndRemoveUntil(MaterialPageRoute(
                      //   builder: (context) {
                      //     return Tabs(tabindex: 2);
                      //   },
                      // ), (route) => false);
                    },
                    child: Text(StringStyles.login.tr)),
              ),
              Container(
                margin: const EdgeInsets.only(top: 10),
                width: 320,
                child: ElevatedButton(
                    onPressed: () {
                      // Navigator.of(context).pushAndRemoveUntil(MaterialPageRoute(
                      //   builder: (context) {
                      //     return Tabs(tabindex: 2);
                      //   },
                      // ), (route) => false);
                    },
                    child: Text('${StringStyles.forgetPwd.tr}？')),
              )
            ],
          ),
        ),
      ),
    );
  }
}
